<?php
class App_Tpl_Form_Field_Localfile extends App_Tpl_Form_Field{

	protected $_imageExts = array('jpg', 'jpeg', 'gif', 'png');

	public function PreparePost($fieldPostData, $params, $currentVal = null, $fieldId = false)
	{
		$outValue = array();
		if (isset($fieldPostData['current']))
		{
			$currentVal = (array)$currentVal;
			if (isset($currentVal['file']) && ($currentVal['file'] == $fieldPostData['current']))
			{
				$outValue = $currentVal;
			}
			else if ($fieldId)
			{
				$savedFile = Mozg_Mapper::Get('Uploads')->GetOne(array('fieldId' => $fieldId, 'path' => $fieldPostData['current']));
				if ($savedFile)
				{
					$outValue = $this->GetFileData($savedFile->GetPath());
				}
			}
		}

		$fieldPostData = $fieldPostData['file'];

		if (isset($fieldPostData['size']))
		{
			$error = $this->ValidateUploadedFile($fieldPostData, $params);
			if ($error === false)
			{
				$uploadFolder = $this->ReplacePathMarkers($params['folder']);

				$origFileName = str_replace(array(' ', "\r", "\n", '.', ','), '_', pathinfo($fieldPostData['name'], PATHINFO_FILENAME));
				$ext = pathinfo($fieldPostData['name'], PATHINFO_EXTENSION);
				$newFileName = str_replace(array('{orig}', '{uniq}'), array($origFileName, str_replace('.', '_', uniqid('', true))), $params['filename']);
				$newFileName = $this->ReplacePathMarkers($newFileName).($ext ? '.' .$ext : '');

				$newFullFilePath = $uploadFolder.$newFileName;

				$saved = false;

				if (Mozg::Lib('Dir')->Create(_ROOT_PATH.$uploadFolder))
				{
					//img
					if ($this->TestImageExt($ext))
					{
						$fileObj = Mozg::Lib('image')->GetImage($fieldPostData['tmp_name']);
						if ($fileObj && $fileObj->IsImage())
						{
							$imageInfo = $fileObj->GetImageInfo();
							$maxImageSize = isset($params['maximgsize']) ? (array)$params['maximgsize'] : array(10000000, 10000000);
							if (($imageInfo[0] <= $maxImageSize[0]) && ($imageInfo[1] <= $maxImageSize[1]))
							{
								$resizeTo = isset($params['resizeto']) ? (array)$params['resizeto'] : array(10000000, 10000000);
								$newFileName = $fileObj->Resize(_ROOT_PATH.$uploadFolder, $newFileName, $resizeTo);
								if (!$fileObj->IsError())
								{
									$saved = true;
								}
								else
								{
									$outValue['error'] = $fileObj->GetError();
								}
							}
							else
							{
								$outValue['error'] = Mozg_Lang::_('Max image size %s', $maxImageSize[0]. 'x' .$maxImageSize[1]. 'px');
							}
						}
						else
						{
							$outValue['error'] = $fileObj->GetError();
						}
					}
					else if (Mozg::Lib('Dir')->MoveUploadedFile($fieldPostData['tmp_name'], _ROOT_PATH.$newFullFilePath))
					{
						$saved = true;
					}
					else
					{
						$outValue['error'] = Mozg_Lang::_('Unable to save file');
					}
				}
				else
				{
					$outValue['error'] = Mozg_Lang::_('Unable to save file');
				}

				if ($saved)
				{
					$outValue = $this->GetFileData($newFullFilePath);

					//save file to Uploads table
					$obj = Mozg_Mapper::Get('Uploads')->GetEntity();
					$obj->SetPath($newFullFilePath);
					$obj->SetFieldId($fieldId);
					Mozg_Mapper::Get('Uploads')->Save($obj);
				}
			}
			else
			{
				$outValue['error'] = Mozg_Lang::_($error);
			}
		}

		return $outValue;
	}

	protected function TestImageExt($ext)
	{
		return in_array(strtolower($ext), $this->_imageExts);
	}

	protected function GetFileData($file)
	{
		return array('file' => $file , 'filesize' => filesize(_ROOT_PATH.$file));
	}

	protected function ReplacePathMarkers($path)
	{
		return str_replace(array('%Y', '%m', '%d', '%H', '%i'), array(date('Y'), date('m'), date('d'), date('H'), date('i')), $path);
	}

	protected function ValidateUploadedFile($fieldPostData, $params)
	{
		$error = false;
		if ($fieldPostData['error'] == UPLOAD_ERR_OK)
		{
			if ($fieldPostData['size'] > $params['maxfilesize'])
			{
				$error = 'Filesize should not be more than ' .$params['maxfilesize']. 'B';
			}
			else if ($params['filetypes'] && ($params['filetypes'] != '*'))
			{
				$fileTypes = array_map('strtolower', array_map('trim', explode(',', $params['filetypes'])));
				$fileExt = strtolower(pathinfo($fieldPostData['name'], PATHINFO_EXTENSION));
				if (!in_array($fileExt, $fileTypes))
				{
					$error = 'File type is not allowed';
				}
			}
		}
		else
		{
			$error = $this->GetUploadErrorMessage($fieldPostData['error']);
		}

		return $error;
	}

    protected function GetUploadErrorMessage($errorCode)
    {
        switch ($errorCode)
        {
            case UPLOAD_ERR_FORM_SIZE:
            case UPLOAD_ERR_INI_SIZE:
	            $m = 'UPLOAD_FILE_SIZE_EXCEEDED';
	            break;

            case UPLOAD_ERR_PARTIAL:
                $m = 'FILE_WAS_UPLOADED_PARTIALLY';
                break;

            case UPLOAD_ERR_NO_FILE:
                $m = 'FILE_WAS_NOT_UPLOADED';
                break;

            default: $m = 'UNKNOWN_ERROR';

        }

        return $m;
    }

	public function PrepareOut($fieldData, $params)
	{
		$fieldData = (array)$fieldData;
		$fieldData = array(
                                'file' => $fieldData['file'],
                                'filesize' => (int)$fieldData['filesize'],
		);

		return $fieldData;
	}

	protected $_defaultFileIcon = 'default.icon.gif';
	protected $_fileIcons = array(
		'ai' => 'ai.gif',
		'avi' => 'avi.gif',
		'bmp' => 'bmp.gif',
		'cs' => 'cs.gif',
		'dll' => 'dll.gif',
		'doc' => 'doc.gif',
		'docx' => 'docx.gif',
		'exe' => 'exe.gif',
		'fla' => 'fla.gif',
		'gif' => 'gif.gif',
		'jpg' => 'jpg.gif',
		'jpeg' => 'jpg.gif',
		'js' => 'js.gif',
		'mdb' => 'mdb.gif',
		'mp3' => 'mp3.gif',
		'pdf' => 'pdf.gif',
		'ppt' => 'ppt.gif',
		'pptx' => 'pptx.gif',
		'rdp' => 'rdp.gif',
		'swf' => 'swf.gif',
		'swt' => 'swt.gif',
		'txt' => 'txt.gif',
		'vsd' => 'vsd.gif',
		'xls' => 'xls.gif',
		'xlsx' => 'xlsx.gif',
		'xml' => 'xml.gif',
		'zip' => 'zip.gif',
	);

	protected function GetFileThumb($filePath, $showImgThumb = false)
	{
		$thumb = '';

		$ext = pathinfo($filePath, PATHINFO_EXTENSION);
		if ($showImgThumb && $this->TestImageExt($ext))
		{
			$thumb = _ROOT_URL_STATIC.Mozg_Mapper::Get('Image')->GetImageThumbFolder('mediathumbnail').$filePath;
		}
		else
		{
			$icon = $this->_defaultFileIcon;
			if (isset($this->_fileIcons[$ext])) $icon = $this->_fileIcons[$ext];

			$thumb = _ROOT_URL_STATIC. 'static/files/images/admin/icons/apps/' .$icon;
		}

		return $thumb;
	}

	public function GetThumbnailBlock($path, $fieldName, $showImgThumb = false)
	{
		$this->filePath = $path;
		$this->fieldName = $fieldName;
		$this->showImgThumb = $showImgThumb;
		return $this->render('form/field/localfile/_thumb.phtml');
	}

    protected function RenderField()
    {
    	return $this->render('form/field/_localfile.phtml');
    }

}